package net.wanho.filter;

import cn.hutool.json.JSONUtil;
import net.wanho.vo.AjaxResult;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 黑名单过滤器
 */
@Component
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUrlFilter.Config> {

    // 指定配置的类型
    public BlackListUrlFilter(){
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            System.out.println("BlackListUrlFilter.filter...........................");

            String url = exchange.getRequest().getURI().getPath();
            // if (url.equals("/users/list")){ // 如果是黑名单中的url，则拦截
            if(config.getBlacklistUrl().contains(url)){
                ServerHttpResponse res = exchange.getResponse();
                String jsonStr = JSONUtil.toJsonStr(AjaxResult.error(HttpStatus.FORBIDDEN.value(),"请求地址不允许访问"));
                DataBuffer buffer = res.bufferFactory().wrap(jsonStr.getBytes(StandardCharsets.UTF_8));
                res.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return res.writeWith(Mono.just(buffer));
            }
            return chain.filter(exchange);
        };
    }

    public static class Config{

        private List<String> blacklistUrl = new ArrayList<>();

        public List<String> getBlacklistUrl() {
            return blacklistUrl;
        }

        public void setBlacklistUrl(List<String> blacklistUrl) {
            this.blacklistUrl = blacklistUrl;
        }
    }
}